package com.order.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    private final SecretKey signKey;

    public JwtUtil(@Value("${jwt.secret}") String secret) {
        this.signKey = Keys.hmacShaKeyFor(secret.getBytes());
    }

    private SecretKey getSignKey() {
        return signKey;
    }

    /**
     * 生成JWT token
     */
    public String generateToken(Long userId, String username, Integer roleType) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("roleType", roleType);
        return createToken(claims, username);
    }

    /**
     * 创建token
     */
    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(getSignKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 从token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();
    }

    /**
     * 从token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return Long.valueOf(claims.get("userId").toString());
    }

    /**
     * 从token中获取角色类型
     */
    public Integer getRoleTypeFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return Integer.valueOf(claims.get("roleType").toString());
    }

    /**
     * 从token中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimsFromToken(token).getExpiration();
    }

    /**
     * 从token中获取Claims
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSignKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 判断token是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Date expiration = getExpirationDateFromToken(token);
            return expiration.before(new Date());
        } catch (ExpiredJwtException e) {
            return true;
        } catch (Exception e) {
            throw new RuntimeException("Token验证失败: " + e.getMessage());
        }
    }

    /**
     * 验证token并返回验证结果信息
     */
    public String validateTokenWithMessage(String token, String username) {
        try {
            String tokenUsername = getUsernameFromToken(token);
            if (!username.equals(tokenUsername)) {
                return "Token用户信息不匹配";
            }
            if (isTokenExpired(token)) {
                return "Token已过期，请重新登录";
            }
            return "Token验证成功";
        } catch (ExpiredJwtException e) {
            return "Token已过期，请重新登录";
        } catch (Exception e) {
            return "Token验证失败: " + e.getMessage();
        }
    }

    /**
     * 验证token（兼容原有方法）
     */
    public Boolean validateToken(String token, String username) {
        String result = validateTokenWithMessage(token, username);
        return "Token验证成功".equals(result);
    }
}